/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.startup.musicstore.services.crud.Impl;

import com.startup.musicstore.model.Album;
import com.startup.musicstore.model.AlbumCategory;
import com.startup.musicstore.services.crud.AlbumCategoryCrudService;
import com.startup.musicstore.services.crud.InventoryService;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author given
 */
public class InventoryServiceImpl implements InventoryService{
    private static ApplicationContext ctx;
    
    @Override
    public String getMessage(int orderQuantity, Long albumID, Long albumCategoryID) {
        ctx = new ClassPathXmlApplicationContext("classpath:com/startup/musicstore/app/conf/applicationContext-*.xml");
        AlbumCategoryCrudService albumCategoryCrudService = (AlbumCategoryCrudService)ctx.getBean("albumCategoryCrudService");
        AlbumCategory albumCategory = albumCategoryCrudService.findById(albumCategoryID);
        List<Album>  albums = albumCategory.getAlbums();
        String updated = "notUpdated";
        
        for(Album a: albums){
            if(albumID.equals(a.getId())){
                a.setInventory(a.getInventory() - orderQuantity);
                a.setSales(a.getSales() + orderQuantity);
                updated = "updated";
            }
        }
        
        albumCategory.setAlbums(albums);
        albumCategoryCrudService.merge(albumCategory);
        
        return updated;
    }
    
}
